#pragma once
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdarg.h>//可变参数列表
#include <unistd.h>
#define SIZE 1024

#define Info 0
#define Debug 1
#define Warning 2
#define Error 3 
#define Fatal 4

#define Screen 1
#define Onefile 2
#define Classfile 3

#define LogFile "log.txt"//文件名

class Log{
public:
    Log(){
        printMethod=Screen;
        path="./log/";
    }
    void Enable(int method){//确定，屏幕，一个文件，多个文件
        printMethod=method;
    }
    std::string levelToString(int level){
        switch(level){
            case Info:
                return "Info";
            case Debug:
                return "Debug";
            case Warning:
                return "Warning";
            case Error:
                return "Error";
            case Fatal:
                return "Fatal";
            default:
                return "None";
        }
    }

    void printLog(int level, const std::string &logtxt){
        switch (printMethod)
        {
        case Screen:
            std::cout<<logtxt<<std::endl;
            break;
        case Onefile:
            printOneFile(LogFile,logtxt);
            break;
        case Classfile:
            printClassFile(level,logtxt);
            break;
        default:
            break;
        }
        
    }

    void printOneFile(const std::string &logname,const std::string &logtxt){//最底层的成员函数，向fd(_logname路径的文件)中写入，logtxt的字符串
        std::string _logname = path+logname;
        int fd=open(_logname.c_str(),O_WRONLY|O_RDONLY|O_CREAT|O_APPEND,0666);//表示：如果找不到路径就表示无法打开错误
        if(fd<0) return;
        write(fd,logtxt.c_str(),logtxt.size());
        close(fd);
    }

    void printClassFile(int level, const std::string &logtxt){//封装printOneFile
        std::string filename = LogFile;
        filename +=".";
        filename += levelToString(level);
        printOneFile(filename,logtxt);
    }

    ~Log(){}

    void operator()(int level, const char* format, ...){
        time_t t=time(nullptr);
        struct tm* ctime = localtime(&t);
        char leftbuffer[SIZE];
        snprintf(leftbuffer,sizeof(leftbuffer),"[%s][%d-%d-%d %d:%d:%d]",levelToString(level).c_str(),
            ctime->tm_year+1900, ctime->tm_mon+1,ctime->tm_mday,
            ctime->tm_hour,ctime->tm_min,ctime->tm_sec);
        
        va_list s;//va_list是char*指针
        va_start(s,format);//初始化可变参数s
        char rightbuffer[SIZE];
        vsnprintf(rightbuffer,sizeof(rightbuffer),format,s);//s以format的格式写入rightbuffer里面，这个是一个传递，可变参数列表的技巧（方法）
        va_end(s);

        //格式： 默认部分+自定义部分
        char logtxt[SIZE*2];
        snprintf(logtxt,sizeof(logtxt),"%s %s\n",leftbuffer,rightbuffer);
        printLog(level, logtxt);
    }

private:
    int printMethod;
    std::string path;
};  

Log lg;